<template>
  <div class="home">
    <div class="banner" id="banner">
      <home-swiper :imgurl="imgUrl"></home-swiper>
    </div>
    <div class="main">
      <home-goods
        class="goods"
        v-for="item in views"
        :key="item.id"
        :item="item"
        :id="item.name"
      ></home-goods>
    </div>
    <div class="nav" id="nav" v-if="showNav">
      <home-nav
        v-for="(item, index) in views"
        :key="item.id"
        :item="item"
        :is-active="currentIndex === index"
        @click="toggle(index)"
      ></home-nav>
    </div>
  </div>
</template>

<script>
import { GetHome } from '@/api'
import homeSwiper from './swiper.vue'
import homeGoods from './goods.vue'
import homeNav from './nav.vue'
export default {
  data() {
    return {
      pcBannerList: [],
      views: [],
      imgUrl: [],
      currentIndex: 0,
      showNav: false, // 新增导航显示控制变量
      bannerHeight: 0 // 用于存储banner高度
    }
  },
  methods: {
    toggle(index) {
      this.currentIndex = index
    },
    updateActive() {
      const links = [...document.querySelectorAll('nav a')]
      const tops = links.map(
        (l) => document.getElementById(l.dataset.target).offsetTop
      )
      const scrollTop = window.pageYOffset
      let idx = 0
      for (let i = tops.length - 1; i >= 0; i--) {
        if (scrollTop >= tops[i]) {
          idx = i
          break
        }
      }
      links.forEach((a, i) => a.classList.toggle('active', i === idx))

      // 新增导航显示控制逻辑
      // 当滚动位置超过banner高度时显示导航，否则隐藏
      this.showNav = scrollTop - 400 > this.bannerHeight
    }
  },
  mounted() {
    // 获取banner元素高度
    this.bannerHeight = document.querySelector('.banner').offsetHeight

    window.addEventListener('scroll', this.updateActive, { passive: true })
    this.updateActive() // 初始
  },
  beforeDestroy() {
    // 清理事件监听
    window.removeEventListener('scroll', this.updateActive)
  },
  components: {
    homeSwiper,
    homeGoods,
    homeNav
  },
  async created() {
    try {
      const {
        result: { pcBannerList, views }
      } = await GetHome()
      this.pcBannerList = pcBannerList
      this.views = views
      this.imgUrl = this.pcBannerList.map((item) => item.imgUrl)
      // console.log(pcBannerList, views, this.imgUrl)
    } catch (error) {
      console.log(error.message)
    }
  }
}
</script>

<style scoped>
.home {
  display: flex;
  flex-direction: column;
  flex-wrap: nowrap;
  position: relative;
  /* border: 1px solid #000; */
}
.home .banner {
  /* border: 1px solid #00ff55; */
}
.home .main {
  width: 2000px;
  margin: auto;
  display: flex;
  flex-direction: column;
  /* border: 1px solid #ff0000; */
}
.nav {
  position: fixed;
  right: 300px;
  top: 500px;
  z-index: 99;
}
</style>
